package com.miracle9.game.util;

import net.sf.json.JSONObject;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;

import java.net.URLEncoder;

public class FangYiUtil {

    public static String fangyi(String msg){
        try {
            int statusCode = 0;
            String result=null;
            String apikey = "cb316e272e4f97a58bc9561c557ce650";
            String apiurl = "https://api.niutrans.com/NiuTransServer/translation?from=zh&to=en&apikey=" + apikey +  "&src_text="+ URLEncoder.encode(msg,"utf-8");
            HttpClient client = new HttpClient();
            GetMethod method = new GetMethod(apiurl);
            method.addRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=" + "utf-8");
            statusCode = client.executeMethod(method);
            if (statusCode != HttpStatus.SC_OK) {// 打印服务器返回的状态
                System.out.println("Method failed: " + method.getStatusLine());
            }
            // 返回响应消息
            byte[] responseBody = method.getResponseBodyAsString().getBytes(method.getResponseCharSet());
            // 在返回响应消息使用编码(utf-8)
            String response = new String(responseBody, "utf-8");
            //        System.out.println("------------------response:" + response);
            // 释放连接
            method.releaseConnection();
            JSONObject json = JSONObject.fromObject(response);
            if (response.indexOf("tgt_text") != -1)
                result = json.get("tgt_text").toString();
           return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
